package com.ht.aems.fesmonitor;

import com.ht.aems.communicate.PipeClosingListener;
import com.ht.aems.communicate.SerializablePipe;
import com.ht.aems.communicate.UdpSerializablePipe;
import org.apache.log4j.Logger;

import java.io.Serializable;
import java.net.SocketException;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2011-4-8
 */
public class FesUdpPipe implements PipeClosingListener {
    private static Logger log = Logger.getLogger(FesUdpPipe.class);

    private int clientPort = 3212;

    private static FesUdpPipe instance;

    private UdpSerializablePipe pipe;

    private FesUdpPipe() {
    }

    public static FesUdpPipe getInstance() {
        if (instance == null) {
            instance = new FesUdpPipe();
        }
        return instance;
    }

    public void start() {
        if (pipe != null && !pipe.isStop()) {
            log.info("Fes UDP server has already been running.");
            return;
        }
        try {
            pipe = new UdpSerializablePipe(clientPort);
            pipe.addPipeClosingListener(this);
        } catch (SocketException e) {
            log.warn("Socket exception :" + e);
        }
    }

    public void stop() {
        if (pipe != null)
            pipe.close();
    }

    public synchronized void send(Serializable obj) {
        try {
            if (pipe != null && !pipe.isStop())
                pipe.write(obj);
        } catch (Exception e) {
            log.warn("Exception :" + Arrays.toString(e.getStackTrace()));
        }
    }


    public UdpSerializablePipe getPipe() {
        return pipe;
    }

    public void pipeClosing(SerializablePipe serializablePipe) {
        log.info("FES UDP pipe is closing");
    }

    public int getClientPort() {
        return clientPort;
    }

    public void setClientPort(int clientPort) {
        this.clientPort = clientPort;
    }
}
